﻿/****************************************************************************
Copyright (c) 2011-2013,WebJet Business Division,CYOU

http://www.genesis-3d.com.cn

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

using System;
using System.Runtime.CompilerServices;
using ScriptRuntime;
namespace ScriptRuntime
{
    public class RefractiveWaterRender : ScriptableClass
    {
        Camera reflectCam;
        Camera refractCam;

        RenderToTexture reflectRtt;
        RenderToTexture refractRtt;
        RenderToTexture lightlit;

        private float m_ClipPlaneOffset = 0.0f;

        public Vector4 m_WaveMapVelocity0 = new Vector4(0.09f, 0.06f, 0.0f, 0.0f);
        public Vector4 m_WaveMapVelocity1 = new Vector4(-0.05f, 0.08f, 0.0f, 0.0f);

        private Vector4 m_WaveMapOffset0;
        private Vector4 m_WaveMapOffset1;


        private Matrix44 Reflect(Vector4 plane)
        {
            Matrix44 matout = new Matrix44();
            matout[0, 0] = -2.0f * plane.X * plane.X + 1.0f;
            matout[0, 1] = -2.0f * plane.X * plane.Y; 
            matout[0, 2] = -2.0f * plane.X * plane.Z;
            matout[0, 3] = -2.0f * plane.X * plane.W; 

            matout[1, 0] = -2.0f * plane.Y * plane.X; 
            matout[1, 1] = -2.0f * plane.Y * plane.Y + 1.0f; 
            matout[1, 2] = -2.0f * plane.Y * plane.Z;
            matout[1, 3] = -2.0f * plane.Y * plane.W;

            matout[2, 0] = -2.0f * plane.Z * plane.X; 
            matout[2, 1] = -2.0f * plane.Z * plane.Y; 
            matout[2, 2] = -2.0f * plane.Z * plane.Z + 1.0f; 
            matout[2, 3] = -2.0f * plane.Z * plane.W;
            matout[3, 0] = 0.0f; matout[3, 1] = 0.0f; matout[3, 2] = 0.0f; matout[3, 3] = 1.0f;
            return matout;
        }

        private void CreateReflect()
        {
            int width = GraphicSystem.GetWidth();
            int height = GraphicSystem.GetHeight();
            Vector4 color = new Vector4(0.25f,0.25f,0.25f,1.0f);


            reflectRtt = new RenderToTexture();
            reflectRtt.Setup(width / 2, height / 2, PixelFormat.X8R8G8B8, ClearFlag.ClearAll, ref color, true);



            reflectCam = new Camera();
            reflectCam.SetupPerspectiveFovRH(0.75f, width / height, 1.0f, 10000.0f);
            reflectCam.SetRenderTarget(reflectRtt);
            reflectCam.SetLightLitTexture(lightlit);
            reflectCam.RenderDepth = false;
            reflectCam.RenderNormal = true;
            reflectCam.RenderCustomised = true;
            reflectCam.CullMask = LayerFlag.Default;
            reflectCam.UseBeforeDrawEvent = false;
            reflectCam.RenderShadowMap = false;
        }

        private void UpdateReflect()
        {
            // find out the reflection plane: position and normal in world space
            Vector3 pos = Owner.WorldPosition;
            Vector3 normal = new Vector3(0.0f, 1.0f, 0.0f);
            float d = -1.0f * Vector3.Dot(normal, pos);
            Vector4 reflectionPlane = new Vector4(normal.X, normal.Y, normal.Z, d);

            CameraComponent mainCam = GraphicSystem.GetSceneCamera();
            Matrix44 mainTrans = Matrix44.Invert(mainCam.ViewTransform);
            //scale
            mainTrans[0, 0] *= -1.0f;
            mainTrans[1, 0] *= -1.0f;
            mainTrans[2, 0] *= -1.0f;
            //reflect
            Matrix44 reflectiveMat44 = Reflect(reflectionPlane);
            Matrix44 reflectTrans = Matrix44.Multiply(Matrix44.Invert(reflectiveMat44), mainTrans);
            reflectCam.ViewTransform = Matrix44.Invert(reflectTrans);
            Vector4 c = Matrix44.TransformVector4(Matrix44.Transpose(reflectTrans), new Vector4(0.0f, 1.0f, 0.0f, d));
            reflectCam.SetupPerspectiveFovRHEx(mainCam.Fov, mainCam.Aspect, mainCam.NearClipPlane, mainCam.FarClipPlane, ref c, true);

        }

        private void CreateRefract()
        {
            int width = GraphicSystem.GetWidth();
            int height = GraphicSystem.GetHeight();
            Vector4 color = new Vector4(0.25f,0.25f,0.25f,1.0f);
            refractRtt = new RenderToTexture();
            refractRtt.Setup(width / 2, height / 2, PixelFormat.A16B16G16R16F, ClearFlag.ClearAll, ref color, true);

            refractCam = new Camera();
            refractCam.SetupPerspectiveFovRH(0.75f, width / height, 1.0f, 10000.0f);
            refractCam.SetRenderTarget(refractRtt);
            refractCam.SetLightLitTexture(lightlit);
            refractCam.RenderDepth = false;
            refractCam.RenderNormal = true;
            refractCam.RenderCustomised = true;
            refractCam.CullMask = LayerFlag.Default;
            refractCam.UseBeforeDrawEvent = false;
            refractCam.RenderShadowMap = false;
        }

        private void UpdateRefract()
        {
            Vector3 pos = Owner.WorldPosition;
            Vector3 normal = new Vector3(0.0f, 1.0f, 0.0f);
            float d = -1.0f * Vector3.Dot(normal, pos);

            CameraComponent mainCam = GraphicSystem.GetSceneCamera();
            Matrix44 mainTrans = Matrix44.Invert(mainCam.ViewTransform);
            //refract
            Vector4 clipPlane = new Vector4(0.0f, -1.0f, 0.0f, -d + m_ClipPlaneOffset);
            refractCam.ViewTransform = mainCam.ViewTransform;
            refractCam.SetupPerspectiveFovRHEx(mainCam.Fov, mainCam.Aspect, mainCam.NearClipPlane, mainCam.FarClipPlane, ref clipPlane, false);

        }

        private void SetupMat()
        {
            m_WaveMapOffset0 = new Vector4();
            m_WaveMapOffset1 = new Vector4();
            //-------------set owner material---------------------//
            MeshRenderComponent meshRenderCom;
            meshRenderCom = Owner.GetComponent<MeshRenderComponent>();
            meshRenderCom.SetTexture(0, "_fresnelMap", "asset:WaterSurface/Media/WaterFresnel.dds", 0);
            meshRenderCom.SetTexture(0, "_waveMap", "asset:WaterSurface/Media/WaterNormal.dds", 0);
            meshRenderCom.SetTexture(0, "_reflectionMap", reflectRtt);
            meshRenderCom.SetTexture(0, "_refractionMap", refractRtt);
            meshRenderCom.SetDrawDepth(false);
        }

        private void UpdataMat()
        {
            float fTick = Util.GetDeltaTime();
            m_WaveMapOffset0 += m_WaveMapVelocity0 * fTick;
            m_WaveMapOffset1 += m_WaveMapVelocity1 * fTick;

            if (m_WaveMapOffset0.X >= 1.0f || m_WaveMapOffset0.X <= -1.0f)
            {
                m_WaveMapOffset0.X = 0.0f;
            }
            if (m_WaveMapOffset1.X >= 1.0f || m_WaveMapOffset1.X <= -1.0f)
            {
                m_WaveMapOffset1.X = 0.0f;
            }
            if (m_WaveMapOffset0.Y >= 1.0f || m_WaveMapOffset0.Y <= -1.0f)
            {
                m_WaveMapOffset0.Y = 0.0f;
            }
            if (m_WaveMapOffset1.Y >= 1.0f || m_WaveMapOffset1.Y <= -1.0f)
            {
                m_WaveMapOffset1.Y = 0.0f;
            }
            MeshRenderComponent meshRenderCom;
            meshRenderCom = Owner.GetComponent<MeshRenderComponent>();
            meshRenderCom.SetShaderConstantParam(0, "gWaveMapOffset0", ref m_WaveMapOffset0);
            meshRenderCom.SetShaderConstantParam(0, "gWaveMapOffset1", ref m_WaveMapOffset1);
            meshRenderCom.SetTexture(0, "_reflectionMap", reflectRtt);
            meshRenderCom.SetTexture(0, "_refractionMap", refractRtt);

        }

        public override void OnWillRenderObject(RenderComponent sender)
        {
            Owner.LayerID = LayerID.Water;
            if (reflectCam == null)
            {
                lightlit = new RenderToTexture();
                Vector4 lightlitColor = Vector4.One;
                lightlit.Setup(1, 1, PixelFormat.X8R8G8B8, ClearFlag.ClearAll, ref lightlitColor, false);

                CreateReflect();
                CreateRefract();
                SetupMat();
            }
  
            UpdateRefract();
            UpdateReflect();
            //---------------------uv offest-----------------------//
            UpdataMat();

            GraphicSystem.RenderCamera(reflectCam);
            GraphicSystem.RenderCamera(refractCam);
        }
    };
}